package com.CST.service.impl.zx;

import com.CST.bo.zx.ProjectSelectBO;
import com.CST.dto.zx.ZxProjectSelectDetailDTO;
import com.CST.entity.cb.BdSysUser;
import com.CST.entity.zx.ZxUserProjectRelation;
import com.CST.mapper.cst.cb.ZXProjectSelectMapper;
import com.CST.mapper.cst.zx.ZX_ViewPersonMapper;
import com.CST.mapper.cst.zx.ZxUserProjectRelationMapper;
import com.CST.service.cb.IBdSysUserService;
import com.CST.service.zx.ZXProjectSelectService;
import com.CST.util.ExcelTransfer;
import com.CST.util.HttpUtil;
import com.CST.util.PageHelperTool;
import com.CST.util.ProjectTimeUtil;
import com.CST.vo.cb.ExcelHead;
import com.CST.vo.cb.ExcelVO;
import com.CST.vo.zx.ZxProjectSelectVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
*@Author 伍文毅
* @Date 2023 03 21 10 58
**/
@Service("zxProjectSelectService")
public class ZXProjectSelectServiceImpl extends ServiceImpl<ZXProjectSelectMapper, ZxProjectSelectVO> implements ZXProjectSelectService{

    @Resource
    private ZXProjectSelectMapper zxProjectSelectMapper;
    @Resource
    private IBdSysUserService iBdSysUserService;
    @Resource
    private ExcelTransfer<ZxProjectSelectVO> zxProjectSelectVOExcelTransfer;

    @Autowired
    private ZxUserProjectRelationMapper zxUserProjectRelationMapper;

    @Autowired
    private ZX_ViewPersonMapper zxViewPersonMapper;

    @Override
    public ZxProjectSelectDetailDTO queryForPage(ProjectSelectBO projectSelectBO) {
        ProjectTimeUtil.setProjectDetailBO(projectSelectBO);
        String userId = HttpUtil.getRequestHeaderInfo("userId");

        BdSysUser userById = iBdSysUserService.getUserById(userId);
        projectSelectBO.setUserId(userById.getUserName());
        String realName = userById.getRealName();

        Map<String, Integer> map = ProjectTimeUtil.operateTime(projectSelectBO.getStartTime(), projectSelectBO.getEndTime());
        Integer startPeriod = map.get("startPeriod");
        Integer endPeriod = map.get("endPeriod");
        projectSelectBO.setStartDate(startPeriod);
        projectSelectBO.setEndDate(endPeriod);
        //获取开始时间的下个月的第一天
        projectSelectBO.setStartTime(projectSelectBO.getStartTime().with(TemporalAdjusters.firstDayOfNextMonth()));
        //获取结束时间的下个月的第一天
        projectSelectBO.setEndTime(projectSelectBO.getEndTime().with(TemporalAdjusters.firstDayOfNextMonth()));

        List<ZxProjectSelectVO> zxProjectSelectVOS = zxProjectSelectMapper.queryForPage(projectSelectBO);
        List<ZxUserProjectRelation> vos = zxUserProjectRelationMapper.inList(userById.getUserName());
        //用户权限配置的对应项目类别id
        List<String> entryCodeList = vos.stream().map(ZxUserProjectRelation::getEntryCode).collect(Collectors.toList());
        zxProjectSelectVOS = zxProjectSelectVOS.stream().filter(t -> entryCodeList.contains(t.getProjectCategoryId())).collect(Collectors.toList());

//        计算项目完成度
        List<ZxProjectSelectVO> list = zxProjectSelectVOS.stream().map(zxProjectSelectVO -> {
//            计算公式分母=> 往期收入（income） + 配套收入（total） + 拨入收入（DialInMoney）
            BigDecimal fenMu = zxProjectSelectVO.getIncome().add(zxProjectSelectVO.getTotal()).add(zxProjectSelectVO.getDialInMoney());
            if(fenMu.compareTo(BigDecimal.ZERO) == 0){
//                分母为0，就默认完成度为0
                zxProjectSelectVO.setProFinishPer(0);
            } else {
//                公式分子-》 总支出
                BigDecimal fenZi = zxProjectSelectVO.getSumOutMoney();
                BigDecimal temp = fenZi.divide(fenMu, RoundingMode.CEILING);
//                1 - 分子 / 分母 * 100 %
                BigDecimal result = BigDecimal.ONE.subtract(temp);
                long longResult =0L;
                if(result.compareTo(BigDecimal.ZERO)>0)
                {
                    longResult =result.multiply(BigDecimal.valueOf(100)).setScale( 0, BigDecimal.ROUND_DOWN ).longValue();
                }
                zxProjectSelectVO.setProFinishPer(longResult);
            }
            return zxProjectSelectVO;
        }).collect(Collectors.toList());

        PageInfo<ZxProjectSelectVO> zxProjectSelectVOPageInfo = PageHelperTool.excutePageInfo(list, projectSelectBO.getPageNo(), projectSelectBO.getPageSize());
        ZxProjectSelectDetailDTO zxProjectSelectDetailDTO = new ZxProjectSelectDetailDTO();
        zxProjectSelectDetailDTO.setZxProjectSelectVOPageInfo(zxProjectSelectVOPageInfo);
        zxProjectSelectDetailDTO.setUserName(realName);
        zxProjectSelectDetailDTO.setDeptName(userById.getDeptName());
        return zxProjectSelectDetailDTO;
    }

    @Override
    public void downloadFile(ProjectSelectBO projectSelectBO, HttpServletResponse response) {
        List<ExcelVO> excel = new ArrayList<>();
//        head
        List<ExcelHead> excelHeads = new ArrayList<>();
        List<String> info1 = new ArrayList<>();
        info1.add("财务编码");
        excelHeads.add(ExcelHead.builder().head("财务编码").cHead(info1).build());
        List<String> info2 = new ArrayList<>();
        info2.add("项目编号");
        excelHeads.add(ExcelHead.builder().head("项目编号").cHead(info2).build());
        List<String> info3 = new ArrayList<>();
        info3.add("项目简称");
        excelHeads.add(ExcelHead.builder().head("项目简称").cHead(info3).build());
        List<String> info4 = new ArrayList<>();
        info4.add("项目全称");
        excelHeads.add(ExcelHead.builder().head("项目全称").cHead(info4).build());
        List<String> info5 = new ArrayList<>();
        info5.add("项目完成度");
        excelHeads.add(ExcelHead.builder().head("项目完成度").cHead(info5).build());
        List<String> info6 = new ArrayList<>();
        info6.add("期初金额");
        excelHeads.add(ExcelHead.builder().head("期初金额").cHead(info6).build());
        List<String> info7 = new ArrayList<>();
        info7.add("是否封存");
        excelHeads.add(ExcelHead.builder().head("是否封存").cHead(info7).build());
        List<String> info8 = new ArrayList<>();
        info8.add("拨入收入");
        info8.add("配套收入");
        info8.add("收入总额");
        excelHeads.add(ExcelHead.builder().head("收入").cHead(info8).build());
        List<String> info9 = new ArrayList<>();
        info9.add("拨入支出");
        info9.add("配套支出");
        info9.add("支出总额");
        excelHeads.add(ExcelHead.builder().head("支出").cHead(info9).build());
        List<String> info10 = new ArrayList<>();
        info10.add("拨入余额");
        info10.add("配套余额");
        info10.add("期末余额");
        excelHeads.add(ExcelHead.builder().head("余额").cHead(info10).build());
        List<List<String>> heads = getHead(excelHeads);
//        data
        ProjectTimeUtil.setProjectDetailBO(projectSelectBO);
        String userId = HttpUtil.getRequestHeaderInfo("userId");
        BdSysUser userById = iBdSysUserService.getUserById(userId);
        projectSelectBO.setUserId(userById.getUserName());

        Map<String, Integer> map = ProjectTimeUtil.operateTime(projectSelectBO.getStartTime(), projectSelectBO.getEndTime());
        Integer startPeriod = map.get("startPeriod");
        Integer endPeriod = map.get("endPeriod");
        projectSelectBO.setStartDate(startPeriod);
        projectSelectBO.setEndDate(endPeriod);
        //获取开始时间的下个月的第一天
        projectSelectBO.setStartTime(projectSelectBO.getStartTime().with(TemporalAdjusters.firstDayOfNextMonth()));
        //获取结束时间的下个月的第一天
        projectSelectBO.setEndTime(projectSelectBO.getEndTime().with(TemporalAdjusters.firstDayOfNextMonth()));

        List<ZxProjectSelectVO> zxProjectSelectVOS = zxProjectSelectMapper.queryForPage(projectSelectBO);
        List<List<Object>> otherData = new ArrayList<>();
        zxProjectSelectVOS.forEach(e -> {
            List<Object> list = new ArrayList<>();
            list.add(e.getFinancialCode());
            list.add(e.getProjectCode());
            list.add(e.getEasyProName());
            list.add(e.getProAllName());
            list.add(e.getProFinishPer());
            list.add(e.getStartMoney());
            list.add(e.getIsClose()==0?"未封存":"已封存");
            list.add(e.getDialInMoney());
            list.add(e.getCompleteInMoney());
            list.add(e.getSumInMoney());
            list.add(e.getDialOutMoney());
            list.add(e.getCompleteOutMoney());
            list.add(e.getSumOutMoney());
            list.add(e.getDialLeftMoney());
            list.add(e.getCompleteLeftMoney());
            list.add(e.getSumLeftMoney());
            otherData.add(list);
        });

        excel.add(ExcelVO.builder().sheet("项目查询首页").listsHead(heads).listsData(otherData).build());
        try {
            zxProjectSelectVOExcelTransfer.exportExcel(response,"项目查询" ,excel);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<List<String>> getHead(List<ExcelHead> headList) {
        List<List<String>> lists = new ArrayList<>();
        headList.forEach(e -> e.getCHead().forEach(c -> {
            List<String> list = new ArrayList<>();
            list.add(e.getHead());
            list.add(c);
            lists.add(list);
        }));
        return lists;
    }
}
